package mess;

public class LeeCode_61 {
    public static void main(String[] args) {
        System.out.println(rotateRight(new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5))))), 2));
        System.out.println(rotateRight(new ListNode(1, new ListNode(2)), 1));
    }

    private static ListNode rotateRight(ListNode head, int k) {
        if (head == null)
            return null;
        int len = 1;
        ListNode mid = head;
        while (mid.next != null){
            len++;
            mid = mid.next;
        }
        if (len == 1)
            return head;

        k %= len;
        k = len - k;
        if (k == 0 || k == len){
            return head;
        }

        ListNode end = head;
        for (int i = 1; i < k; i++) {
            end = end.next;
        }
        ListNode start = end.next;

        mid.next = head;
        end.next = null;

        return start;
    }

    private static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return val + " " + this.next;
        }
    }
}
